package com.netsdk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netsdk.dao.PassengerDao;
import com.netsdk.dao.PassengerRecognitionDao;
import com.netsdk.entity.PassengerDO;
import com.netsdk.entity.PassengerRecognitionDO;
import com.netsdk.entity.R;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.module.FaceRecognitionModule;
import com.netsdk.service.PassengerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class PassengerServiceImpl implements PassengerService {
    public String groupId = "1";
    @Resource
    private PassengerDao passengerDao;
    @Resource
    private PassengerRecognitionDao recognitionDao;

    @Override
    public R queryPassenger(JSONObject params) {
        if (StringUtils.isAnyBlank(params.getString("channel"), params.getString("queryTime"))) {
            return R.error();
        }
        params.put("net_time", params.getString("queryTime"));
        params.remove("queryTime");
        List<PassengerRecognitionDO> list = recognitionDao.selectByMap(params);
        return R.ok().put("passengerUuid",
                CollectionUtils.isEmpty(list) ? "暂无记录" : list.get(0).getPassengerUuid());
    }

    public R uploadPassenger(PassengerDO passengerDO) {
        if (StringUtils.isAnyBlank(passengerDO.getChannel(), passengerDO.getPassengerUuid())) {
            return R.error();
        }
        // 修改人员
        PassengerDO passenger = passengerDao.selectById(passengerDO.getPassengerUuid());
        if (passenger != null) {
            passenger.setPassengerPhotoUrl(passengerDO.getPassengerPhotoUrl());
            passenger.setPhotoUrls(JSON.toJSONString(passengerDO.getPassengerPhotoUrl()));
            boolean success = FaceRecognitionModule.modifyPerson(groupId, passenger);
            int count = passengerDao.updateById(passenger);
            return success && count > 0 ? R.ok() : R.error("DH_SDK修改人员失败！");
        }
        // 添加人员 (szId不能用passengerUuid, 可能长度问题)
        passengerDO.setSzId("44092320000915341x");
        passengerDO.setPersonName(passengerDO.getPassengerUuid());
        passengerDO.setSex(NetSDKLib.EM_SEX_TYPE.EM_SEX_TYPE_MALE);
        passengerDO.setIdType(NetSDKLib.EM_CERTIFICATE_TYPE.CERTIFICATE_TYPE_IC);

        String szUid = FaceRecognitionModule.addPerson(groupId, passengerDO);
        if (StringUtils.isBlank(szUid) || szUid.contains("ERR")) {
            return R.error("DH_SDK添加人员失败: " + szUid);
        }
        // 保存人员
        passengerDO.setSzUid(szUid);
        passengerDO.setPhotoUrls(JSON.toJSONString(passengerDO.getPassengerPhotoUrl()));
        passengerDao.insert(passengerDO);
        return R.ok();
    }
}
